package com.hydra.auth.repository;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hydra.auth.entity.SysOperateLog;
import com.hydra.auth.entity.SysRole;
import com.hydra.auth.entity.SysUser;
import com.hydra.auth.mapper.SysOperateLogMapper;
import com.hydra.auth.mapper.SysUserMapper;
import com.hydra.base.operate.log.annotation.OperateLogInject;
import com.hydra.base.operate.log.entity.BaseOperateLogEntity;
import com.hydra.base.services.BaseService;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class SysUserService extends BaseService<SysUser, SysUserMapper> {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysOperateLogMapper sysOperateLogMapper;

    /**切面进行操作日志记录*/
    @Override
    @OperateLogInject(cate = "SYS_USER")
    public void handleOperateLog(SysUser data, SysUser history) {
        super.handleOperateLog(data, history);
    }

    /**保存操作日志*/
    @Override
    public void saveOperateLog(BaseOperateLogEntity operateLogInfo, SysUser updateData, SysUser historyData) {
        SysOperateLog log = operateLogInfo.copy(SysOperateLog.class);
        sysOperateLogMapper.insert(log);
    }

    /**
     * 匹配用户名、手机号、邮箱进行登录
     */
    public SysUser findByAccount(String username){
        SysUser user = this.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUsername, username)
                .or()
                .eq(SysUser::getEmail, username)
                .or()
                .eq(SysUser::getPhone, username)
                .last("limit 1"));
        //获取权限
        loadSysRole(user);
        return user;
    }

    /**
     * 获取权限
     */
    private void loadSysRole(SysUser user){
        if(user != null){
            List<SysRole> roleList = sysRoleService.findByUserCode(user.getCode());
            user.setRoles(roleList);
        }
    }

    /**
     * 根据用户名查询用户列表信息
     */
    public List<SysUser> findByUsername(String username){
        return this.list(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUsername, username));
    }

    /**
     * 根据邮箱查询用户列表信息
     */
    public List<SysUser> findByEmail(String email){
        return this.list(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getEmail, email));
    }

    /**
     * 根据手机号查询用户列表信息
     */
    public List<SysUser> findByPhone(String phone){
        return this.list(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getPhone, phone));
    }

    /**
     * 根据用户编码列表获取用户列表
     * @param codeList  编码列表
     * @return          用户列表
     */
    public List<SysUser> listUserByCode(List<String> codeList) {
        return this.list(Wrappers.<SysUser>lambdaQuery()
                .in(SysUser::getCode, codeList));
    }
}
